<?php
/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi
 
    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/

class Message extends BaseMessage {
	/**
	 * Delete the message and also delete the message history if there are no other user messages
	 * Basically need to remove orphaned message histories
	 * @see lib/model/om/BaseUserMessage#delete()
	 */
	public function delete(PropelPDO $con = null) {
		$message = parent::delete($con);

		// check and see if there exists other messages with this history id
		$history_id = $this->getMessageHistoryId();
		$c = new Criteria();
		$c->add(MessagePeer::MESSAGE_HISTORY_ID, $history_id);
		$count = MessagePeer::doCount($c);
		if($count == 0) {
			// delete the related message
			$c = new Criteria();
			$c->add(MessageHistoryPeer::ID, $history_id);
			MessageHistoryPeer::doDelete($c);
		}

		return $message;
	}

	public function save(PropelPDO $con = null) {
		
		//hold value before saving
		$new = $this->isNew();

		
		$mailer = null;
		$email_enabled = sfConfig::get('app_group_enable_email', false);
		$context = sfContext::getInstance();
		$context_action = $context->getController()->getAction('default', 'index');
		
		
		// if the message is new and it is sent to a group, build a swift email object
		if($email_enabled && $this->isNew() && $this->getType() == MessagePeer::GROUP_TYPE && $this->getTypeId() && $this->getRecipientId()) { 
			// retrieve the smtp server from the app.yml
			$smtp_server = sfConfig::get('app_smtp_server');
			$smtp_user = sfConfig::get('app_smtp_user');
			$smtp_password = sfConfig::get('app_smtp_password');

			// Create the mailer
			$connection = new Swift_Connection_SMTP($smtp_server, 465, Swift_Connection_SMTP::ENC_SSL);
			$connection->setUsername($smtp_user);
			$connection->setPassword($smtp_password);
			$mailer = new Swift($connection);
		}
		
		$save_status = parent::save($con);
		
		// only send the message if create and saving the message object was successful
		if($save_status && $mailer) {	
			try {
				$displayName = $this->getUserRelatedBySenderId()->getFullName();
				if(!$displayName) {
					$displayName = $this->getUserRelatedBySenderId()->getUsername();
				}
				
				$group = GroupPeer::retrieveById($this->getTypeId());
				
				// Subject line
				$message = new Swift_Message($this->getSubject());
	
				// Render message parts - do a network check to determine which message
				$mailContext = array('message' => $this, 'group' => $group);	// to be passed as parameters to the partials
				$message->attach(new Swift_Message_Part($context_action->getPartial('messages/groupMailMessage', $mailContext), 'text/plain'));	// Plaintext e-mail body
				
				// Set the 'To' and 'From' fields
				$encoded_format = 'U'.$this->getRecipientId().'-S'.$this->getSenderId().'-I'.$this->getId()."-H".$this->getMessageHistoryId();
				if($this->getType() == MessagePeer::GROUP_TYPE) {
					$encoded_format .= "-G".$this->getTypeId();
				}
				$from = $encoded_format . "@".sfConfig::get('app_ratl_address');				
				$mailer->send($message, $this->getUserRelatedByRecipientId()->getEmail(), $from);
				$mailer->disconnect();
			} catch (Exception $e) {
				$context_action->logMessage($e->getMessage(), 'crit');	// Log the exception as critical
			}			
		}
		
		
		//activity feed ======================
		
		if($new){
		$activity_feed = new ActivityFeed();
		
		$activity_feed->setUserId($this->getUserId());
		$activity_feed->setType(ActivityFeedPeer::MESSAGE_TYPE);
		
		if($this->getType() == MessagePeer::GROUP_TYPE)
		{
			$activity_feed->setGroupId($this->getTypeId());
		
			$group = GroupPeer::retrieveById($this->getTypeId());
			
		}
		
		// is this a new task?
		
		$action = "sent";
		
		$message = "<strong>" . $action . " a  message</strong>";	// the rest of the message will be constructed by the RenderFeeds helper
		$activity_feed->setMessage($message);
		
		$activity_feed->setTypeId($this->getId());
		$activity_feed->save();
		}
	//end activity feed=====================

	}
	
	public function getSender()
	{
		
		return UserPeer::retrieveById($this->getSenderId());
	}

}
?>